#!/usr/bin/env python
# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import dbus
import dbus.service

from swindle import entity
from swindle import service


class Device(entity.Entity):
  _I_DEVICE = 'org.chromium.flimflam.Device'

  def __init__(self, mgr, bus, name):
    entity.Entity.__init__(self, bus, '/device/%s' % name)
    self.bus = bus
    self.devid = 0
    self.mgr = mgr
    self._strength = 100
    self._name = name
    self._enabled = False
    self._connected = False
    self._networks = []

  def networks(self):
    return dbus.Array([x.path() for x in self._networks],
                      signature='s', variant_level=1)

  def strength(self):
    return self._strength

  def add_network(self, net):
    self._networks.append(net)
    self.PropertyChanged('Networks', self.networks())

  def del_network(self, net):
    self._networks.remove(net)
    self.PropertyChanged('Networks', self.networks())

  def enable(self):
    self.log('enable')
    self._enabled = True
    self.srv = service.Service(self.bus, self, self.mgr.profile(), '%s_%d' % (
                               self._name, self.devid))
    self.mgr.add_service(self.srv)
    self.PropertyChanged('Powered', dbus.Boolean(True, variant_level=1))

  def disable(self):
    self.log('disable')
    self._enabled = False
    self.mgr.del_service(self.srv)
    self.srv.die()
    self.srv = None
    self.PropertyChanged('Powered', dbus.Boolean(False, variant_level=1))

  def enabled(self):
    return self._enabled

  def connect(self):
    self.log('connect')
    self._connected = True

  def disconnect(self):
    self.log('disconnect')
    self._connected = False

  def connected(self):
    return self._connected

  def technology(self):
    return 'fake'

  def state(self):
    return 'ready'

  def name(self):
    return self._name

  def iface(self):
    return 'fake0'

  @dbus.service.method(_I_DEVICE, in_signature='', out_signature='a{sv}')
  def GetProperties(self):
    self.log('GetProperties')
    r = {}
    r['Name'] = dbus.String(self.name(), variant_level=1)
    r['Type'] = dbus.String(self.technology(), variant_level=1)
    r['Interface'] = dbus.String(self.iface(), variant_level=1)
    r['Powered'] = dbus.Boolean(self.enabled(), variant_level=1)
    r['Reconnect'] = dbus.Boolean(False, variant_level=1)
    if self._networks:
      r['Networks'] = dbus.Array([x.path() for x in self._networks],
                                 variant_level=1)
    return r

  @dbus.service.method(_I_DEVICE, in_signature='sv', out_signature='')
  def SetProperty(self, key, val):
    self.log('SetProperty %s %s', key, val)

  @dbus.service.signal(_I_DEVICE, signature='sv')
  def PropertyChanged(self, key, val):
    self.log('PropertyChanged %s %s', key, val)
